package com.hyfd.deal.Flow;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.hyfd.common.GenerateData;
import com.hyfd.common.utils.MapUtils;
import com.hyfd.common.utils.ToolDateTime;
import com.hyfd.common.utils.ToolHttp;
import com.hyfd.common.utils.XiChengAESUtils;
import com.hyfd.common.utils.XiChengMD5Utils;
import com.hyfd.common.utils.XmlUtils;
import com.hyfd.common.utils.YiGuangAES;
import com.hyfd.deal.BaseDeal;

/**
 * Create Date: 2017年6月20日 下午2:45:42
 * 
 * @version: V3.0.0
 * @author: CXJ
 */
public class YiGuangFlowDeal implements BaseDeal
{
    Logger log = Logger.getLogger(getClass());
    
    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> deal(Map<String, Object> order)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        int flag = -1;
        
        try
        {
            // 手机号
            String mobile = (String)order.get("phone");
            String p_id = (String)order.get("providerProductId");//产品id
            // 平台订单号
            String curids =
                    ToolDateTime.format(new Date(), "yyyyMMddHHmmssSSS") + mobile + GenerateData.getIntData(9, 2);
            map.put("orderId", curids);
            // 账号
            Map<String, Object> channel = (Map<String, Object>)order.get("channel");// 获取通道参数
            String linkUrl = (String)channel.get("link_url");// 充值地址
            String defaultParameter = (String)channel.get("default_parameter");// 默认参数
            Map<String, String> paramMap = XmlUtils.readXmlToMap(defaultParameter);
            String api_userid = paramMap.get("api_userid");// 身份ID
            String securitKey = paramMap.get("securitKey");// 加密key
            String result = byOrder(api_userid, securitKey, p_id, curids, mobile, linkUrl);
            // 组装包体
/*            JSONObject jsonBody = new JSONObject();
            jsonBody.put("api_userid", api_userid);
            jsonBody.put("order_no", curids);
            jsonBody.put("mobile", mobile);
            jsonBody.put("product_id", p_id);
            
            String data = YiGuangAES.encrypt(jsonBody.toString(), securitKey);
//            JSONObject json = new JSONObject();
//            json.put("api_userid", api_userid);
//            json.put("api_data", data);
            String params ="api_uerid="+api_userid+"&api_data="+data;
//            String contentType = "application/x-www-form-urlencoded";
            // post请求
            String result = sendPost(linkUrl, params);*/
            // 判断是否成功
            if (result != null)
            {
                JSONObject jObject = JSONObject.parseObject(result);
                
                String resultCode = jObject.getString("retcode");
                String resultDesc = jObject.getString("retmsg");
                map.put("resultCode", resultCode + ":" + resultDesc);
                // code=0为成功
                if ("200".equals(resultCode))
                {
                    flag = 1;
                }
                else
                {
                    flag = 0;
                }
            }
            else
            {
                flag = 0;
            }
        }
        catch (Exception e)
        {
            log.error("易广流量出错" + e + MapUtils.toString(order));
        }
        map.put("status", flag);
        return map;
    }
    
    public String sendPost(String urls,String param){
        StringBuffer sb=new StringBuffer();
        try{
            URL url = new URL(urls);
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.connect();
            OutputStreamWriter outer = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
            outer.write(param);
            outer.flush();
            outer.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            String inlin="";            
            while ((inlin = in.readLine()) != null) {
                sb.append(inlin);
            }
            in.close();            
        }catch(Exception e){
            e.printStackTrace();
        }
        return sb.toString();
    }
    public String byOrder(String userid,String key,String product,String orderNo, String mobile,String apiUrl) {
        String rets = "";
        StringBuffer sbf = new StringBuffer();
        sbf.append("{");
        sbf.append("\"api_userid\":\"").append(userid).append("\",");
        sbf.append("\"product_id\":\"").append(product).append("\",");
        sbf.append("\"mobile\":\"").append(mobile).append("\",");
        sbf.append("\"order_no\":\"").append(orderNo).append("\"");
        sbf.append("}");
        String jsonstr = sbf.toString();
        jsonstr = YiGuangAES.encrypt(jsonstr, key);    
        String param = (new StringBuilder()).append("api_userid=").append(userid).append("&api_data=").append(jsonstr).toString();    
        rets = sendPost(apiUrl, param);
        return rets;
      }
}
